from sqlalchemy.orm import Session
from . import models, schemas

def get_rule(db: Session, rule_id: int):
    return db.query(models.Rule).filter(models.Rule.Id == rule_id).first()

def get_rules(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.Rule).offset(skip).limit(limit).all()

def create_rule(db: Session, rule: schemas.RuleCreate):
    db_rule = models.Rule(**rule.dict())
    db.add(db_rule)
    db.commit()
    db.refresh(db_rule)
    return db_rule

def update_rule(db: Session, rule_id: int, rule: schemas.RuleCreate):
    db_rule = db.query(models.Rule).filter(models.Rule.Id == rule_id).first()
    if db_rule:
        for key, value in rule.dict().items():
            setattr(db_rule, key, value)
        db.commit()
        db.refresh(db_rule)
    return db_rule

def delete_rule(db: Session, rule_id: int):
    db_rule = db.query(models.Rule).filter(models.Rule.Id == rule_id).first()
    if db_rule:
        db.delete(db_rule)
        db.commit()
    return db_rule